#include "AIPaddle.h"
#include "Game.h"
#include "GameBall.h"
#include <assert.h>


AIPaddle::AIPaddle() :
_velocity(0),
_maxVelocity(600.0f)
{
	Load("images/paddle.png");
	assert(IsLoaded());
	_width = GetSprite().getTextureRect().width;
	_height = GetSprite().getTextureRect().height;

	GetSprite().setOrigin(_width / 2, _height / 2);
}


AIPaddle::~AIPaddle()
{
}

void AIPaddle::Draw(sf::RenderWindow& window)
{
	VisibleGameObject::Draw(window);
}

float AIPaddle::GetVelocity() const
{
	return _velocity;
}

void AIPaddle::Update(float elapsedTime)
{
	const GameBall* gameBall = static_cast<GameBall*> (Game::GetGameObjectCache().Get("Ball"));

	int xMax = Game::SCREEN_WIDTH;
	int yMax = Game::SCREEN_HEIGHT;

	sf::Vector2f pos = GetPosition();
	sf::Vector2f ballPosition = gameBall->GetPosition();

	float xVel = gameBall->GetVelocityX();
	float yVel = gameBall->GetVelocityY();

	float velocityDelta = 600.0f * elapsedTime;

	
	if (yVel < 0)
	{
		float xDelta = pos.x - ballPosition.x;
		if (xDelta < -20)
			_velocity += velocityDelta;// *std::max(xDelta, -20.0f);
		else if (xDelta > 20)
			_velocity -= velocityDelta;// * std::min(xDelta, 20.0f);
		else if (_velocity > 0)
			_velocity -= velocityDelta  * 2.0f;
		else if (_velocity < 0)
			_velocity += velocityDelta  * 2.0f;
		else
			_velocity = 0.0f;

		if (_velocity > _maxVelocity)
			_velocity = _maxVelocity;

		if (_velocity < -_maxVelocity)
			_velocity = -_maxVelocity;
	}
	else
	{
		if (pos.x < Game::SCREEN_WIDTH / 2 - 20)
		{
			_velocity += velocityDelta;
		}
		else if (pos.x > Game::SCREEN_WIDTH / 2 + 20)
		{
			_velocity -= velocityDelta;
		}
		else
		{
			if (_velocity > 0)
				_velocity -= velocityDelta * 5.0f;
			if (_velocity < 0)
				_velocity += velocityDelta * 5.0f;
		}
	}

	if (pos.x < _width / 2)
	{
		pos.x = _width / 2;
		GetSprite().setPosition(pos);
		_velocity = -_velocity / 2;
	}
	if (pos.x >(xMax - _width / 2))
	{
		pos.x = xMax - _width / 2;
		GetSprite().setPosition(pos);
		_velocity = -_velocity / 2;
	}


	GetSprite().move(_velocity * elapsedTime, 0);
}

